/*
 * StringEncodablePersistenceDelegate.java
 *
 * Created on May 26, 2004, 5:22 PM
 *
 * Copyright 2008 the Desert Labs Project (http://desertlabs.us)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package us.desertlabs.beans;

import java.beans.Encoder;
import java.beans.Expression;
import java.beans.PersistenceDelegate;

/**
 * This class represents a <CODE>PersistenceDelegate</CODE> for <CODE>Object</CODE>s
 * that can be constructed with their <CODE>toString</CODE> value.
 *
 * @author Brian Franklin
 */
public class StringEncodablePersistenceDelegate extends PersistenceDelegate {

    /** Singleton instance */
    private static final StringEncodablePersistenceDelegate INSTANCE = new StringEncodablePersistenceDelegate();

    /**
     * Returns the singleton instance.
     *
     * @return the singleton instance
     */
    public static StringEncodablePersistenceDelegate getInstance() {
        return INSTANCE;
    }

    /**
     * Creates a new instance of StringEncodablePersistenceDelegate. This
     * constructor is not public because of the singleton implementation, but it
     * is protected so that subclasses can be constructed if necessary.
     */
    protected StringEncodablePersistenceDelegate() {
    }

    /**
     * Returns an <CODE>Expression</CODE> that instantiates the object by
     * passing the value returned from its <CODE>toString</CODE> method to its
     * constructor.
     *
     * @param obj the instance that will be created by this expression
     * @param encoder the stream to which this expression will be written
     * @return an <CODE>Expression</CODE> whose value is <CODE>obj</CODE>
     */
    @Override
    protected Expression instantiate( final Object obj, final Encoder encoder ) {
        return new Expression( obj, obj.getClass(), "new", new Object[]{
                    obj.toString()
                } );
    }
}
